package com.agv.web.adm.cat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.agv.core.objectDomain.AdmCatalogo;
import com.agv.core.objectDomain.Catalogo;
import com.agv.core.objectDomain.InfoAuditoria;
import com.agv.core.objectDomain.ParamCatalogo;
import com.agv.core.objectDomain.Paso;
import com.agv.core.objectDomain.Usuario;
import com.agv.core.services.ICatalogosService;
import com.agv.core.util.Constantes;
import com.agv.core.util.Util;
import com.agv.web.MonitoringDispatchAction;

public class AdmCatDispatchAction extends MonitoringDispatchAction {

	private ICatalogosService catalogosService;

	public ActionForward irInicio(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			request.getSession().setAttribute("pasoActual", String.valueOf(1));
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward irAtras(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			HttpSession session = request.getSession();
			session.removeAttribute("catCompleto");

			Integer secuenciaActual = Integer.parseInt((String) request
					.getSession().getAttribute("pasoActual"));
			if (secuenciaActual > 1) {
				secuenciaActual = secuenciaActual - 1;
			}
			session.setAttribute("pasoActual", String.valueOf(secuenciaActual));
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward irAdelante(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();
			session.removeAttribute("catCompleto");

			AdmCatForm admCatForm = (AdmCatForm) form;
			Integer secuenciaActual = Integer.parseInt((String) request
					.getSession().getAttribute("pasoActual"));

			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Paso pasoActual = admCatalogo.getPasos().get(secuenciaActual - 1);

			if (pasoActual.getStEstatus().equals(Constantes.COMPLETADO)) {
				Integer totalPasos = (Integer) request.getSession()
						.getAttribute("totalPasos");

				if (secuenciaActual < totalPasos) {
					secuenciaActual = secuenciaActual + 1;
				} else {
					session.setAttribute("catCompleto", "si");
				}
				request.getSession().setAttribute("pasoActual",
						String.valueOf(secuenciaActual));
			} else {
				ActionMessages messages = new ActionMessages();
				ActionMessage msg = new ActionMessage(
						"agv.adm.cat.pasoNoCompletado", secuenciaActual);
				messages.add("message", msg);
				saveMessages(request, messages);
			}

			Integer indice = Integer.parseInt((String) session
					.getAttribute("pasoActual")) - 1;
			Catalogo catalogo = admCatalogo.getCatalogos().get(indice);

			int cont = 0;
			for (String value : admCatForm.getNbPropiedades()) {
				if (!value.equals("")) {
					catalogo.getParams().get(cont).setVlValue(
							admCatForm.getNbPropiedades()[cont]);
				}
				cont++;
			}

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward agregar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			HttpSession session = request.getSession();
			AdmCatForm admCatForm = (AdmCatForm) form;
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");

			Integer indice = Integer.parseInt((String) session
					.getAttribute("pasoActual")) - 1;
			Catalogo catalogo = admCatalogo.getCatalogos().get(indice);
			String nbTabla = catalogo.getNbTabla();
			ArrayList<String> nbCamposDuplicidad = catalogo
					.getNbCamposDuplicidad();

			ActionMessages messages = new ActionMessages();

			int cont = 0;
			for (String value : admCatForm.getNbPropiedades()) {
				if (value.equals("")) {
					ActionMessage msg = new ActionMessage(
							"agv.adm.cat.campoRequerido");
					messages.add("message", msg);
					saveMessages(request, messages);
					admCatForm.getNbPropiedades()[cont] = null;
					return mapping.findForward("cfgCatalogos");
				} else {

					boolean resValidacion = false;
					String tpValidacion = catalogo.getParams().get(cont)
							.getTpValidacion();
					String nbCampo = catalogo.getParams().get(cont)
							.getNbCampoTabla();

					if (tpValidacion != null) {
						if (tpValidacion.equals(Constantes.VALIDACION_ALFA)) {
							resValidacion = Util.validarAlfa(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_ALFA_NUM)) {
							resValidacion = Util.validarAlfaNumerico(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_CORREO)) {
							resValidacion = Util.validarCorreo(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_NUM)) {
							resValidacion = Util.validarNumerico(admCatForm
									.getNbPropiedades()[cont]);
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_FECHA)) {
							resValidacion = true;
						} else if (tpValidacion
								.equals(Constantes.VALIDACION_DECIMAL)) {
							resValidacion = true;
						}

						catalogo.getParams().get(cont).setVlValue(
								admCatForm.getNbPropiedades()[cont]);

						if (!resValidacion) {
							messages = new ActionMessages();
							ActionMessage msg = new ActionMessage(
									"agv.adm.cat.formato", catalogo.getParams()
											.get(cont).getNbLeyenda());
							messages.add("message", msg);
							saveMessages(request, messages);
						}

						if (nbCamposDuplicidad.contains(nbCampo)
								&& session.getAttribute("actualizarCatalogo") == null) {
							boolean res = catalogosService.validaDuplicidad(
									nbCampo, value, nbTabla);
							if (res) {
								messages = new ActionMessages();
								ActionMessage msg = new ActionMessage(
										"agv.adm.cat.duplicidad", catalogo
												.getParams().get(cont)
												.getNbLeyenda());
								messages.add("message", msg);
								saveMessages(request, messages);
							}
						}

					} else {
						catalogo.getParams().get(cont).setVlValue(
								admCatForm.getNbPropiedades()[cont]);
					}
				}
				cont++;
			}

			if (!messages.isEmpty()) {
				return mapping.findForward("cfgCatalogos");
			}

			admCatalogo.getPasos().get(indice).setStEstatus(
					Constantes.COMPLETADO);
			request.getSession().setAttribute("pasoActual",
					String.valueOf(indice + 2));
			if ((indice + 1) == admCatalogo.getPasos().size()) {
				request.getSession().setAttribute("catCompleto", "si");
			}
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}

	}

	public ActionForward insertarCatBd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();
			session.setAttribute("catInsertado", "si");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.insertarCatalgoBD(admCatalogo, usuario
					.getIdUsuario());
			admCatalogo.setStEstatus(Constantes.COMPLETADO);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward borrar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			HttpSession session = request.getSession();

			Integer index = Integer.parseInt(request.getParameter("index")) - 1;
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbCampoId = catalogo.getNbCampoId();
			Integer vlValorId = Integer.parseInt(reg.get(nbCampoId));

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.borrarCatalgoBD(admCatalogo, usuario
					.getIdUsuario(), vlValorId, catalogo.getNbCampoEstatus());

			session.setAttribute("catBorrado", "si");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward actualizar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			request.getSession().removeAttribute("buscaCatalogo");
			request.getSession().setAttribute("altaCatalogo", "si");
			request.getSession().setAttribute("actualizarCatalogo", "si");
			Integer index = Integer.parseInt(request.getParameter("index")) - 1;

			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			for (ParamCatalogo paramCatalogo : catalogo.getParams()) {
				paramCatalogo.setVlValue(reg.get(
						paramCatalogo.getNbCampoTabla()).trim());
			}

			request.getSession().setAttribute("index", index);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward actualizarCatBd(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			HttpSession session = request.getSession();

			Integer index = (Integer) request.getSession()
					.getAttribute("index");
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbCampoId = catalogo.getNbCampoId();
			Integer vlValorId = Integer.parseInt(reg.get(nbCampoId));

			Usuario usuario = (Usuario) session.getAttribute("usuarioObj");

			catalogosService.actualizarCatalgoBD(admCatalogo, usuario
					.getIdUsuario(), vlValorId);
			admCatalogo.setStEstatus(Constantes.COMPLETADO);

			session.setAttribute("catInsertado", "si");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public ActionForward buscar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			String vlValor = request.getParameter("paramBusquedaCat");
			request.getSession().setAttribute("paramBusquedaCat", vlValor);

			request.getSession().setAttribute("buscaCatalogo", "si");
			request.getSession().removeAttribute("altaCatalogo");
			request.getSession().removeAttribute("actualizarCatalogo");
			request.getSession().removeAttribute("catInsertado");
			request.getSession().removeAttribute("catCompleto");

			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward consultaInfoAuditoria(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			Integer index = Integer.parseInt(request.getParameter("index")) - 1;
			List<Map<String, String>> mapa = (List<Map<String, String>>) request
					.getSession().getAttribute("mapaObj");
			AdmCatalogo admCatalogo = (AdmCatalogo) request.getSession()
					.getAttribute("catalogoObj");
			Catalogo catalogo = admCatalogo.getCatalogos().get(0);
			Map<String, String> reg = mapa.get(index);

			String nbTabla = catalogo.getNbTabla();
			String nbCampoId = catalogo.getNbCampoId();
			String vlValorId = reg.get(nbCampoId);

			InfoAuditoria infoAuditoria = catalogosService
					.consultaInfoAuditoria(nbTabla, nbCampoId, vlValorId);
			request.setAttribute("infoAuditoriaObj", infoAuditoria);
			return mapping.findForward("cfgCatalogos");
		} catch (Exception e) {
			monitoringError(request, e);
			log.error(e, e);
			return mapping.findForward(Constantes.FWD_ERR);
		}
	}

	public void setCatalogosService(ICatalogosService catalogosService) {
		this.catalogosService = catalogosService;
	}

}
